<?

//Initiate Authenticate
SecurityRedirect ();
//error_reporting(E_ALL);


//initiate Vars
define("PRIMARY_KEY","upload_doc_id");
$FileName       = "ais_transaction_shipping_doc.php";
$FileTemplate   = "ais_transaction_shipping_doc_uploadFile.html";
$SubHeaderTitle = "Shipping Document";
$TableName      = "tblshipping_doc_upload";
$HTMLFormName   = "JOForm";
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");

$ServerURL = ServerURL;
$uploadDirModule = "shippingDoc";
$upload_dir = $ROOT_DIR.$ROOT_UPLOAD_DIR."/".$uploadDirModule."/";

$MaxGrid        = "20";
$KTRASL                = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("jo_id"=>"","file_upload"=>"");
buildsqlfield ("$TableName", $FormFields);


//Variable declaration
$jo_id = GetParam("jo_id","");
$project_id = GetParam("project_id","");
$PageSize = 1;


$today = date("Y-m-d");

//End Variable declaration


//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name");
$FormCValue    = BuildHTMLField($FormFields,"value");
$FormHName     = BuildHTMLField($FormFields,"name",1);
$FormHValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************


if (GetParam("FormAction","")=="Save") 
{
				
	  FormSave("tblshipping_doc_upload", "no", array("jo_id"=>"","file_upload"=>""),"","jo_id",$jo_id);

	  $DBConnection->InsertGrid();				
	
	  SetLogActivity($TransNo,"Create","");
  
	  
	  if(!empty($strError))  		  
	  {
		 jsAlert($strError);	
	  }
	  
	  redirectMeta($FileName."?PageMode=uploadFile&jo_id=".$jo_id);
	  exit;
	
}

else if (GetParam("FormAction","")=="delete_file") 
{	
	DeleteRecord("txtCheck",$MaxGrid);		
}






//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";


//$VerifyFields = array("services_id1" => "Services","qty1" => "Quantity","unit1"=>"Unit","curr1"=>"Currency","rate1"=>"Rate");

$VerifyFields = array();
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar);


$InitFunction = "Masking();Masking2();";

$VerifyGrids = array();
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array(),"2");
$JSMasks  = $Masking1.$Masking2;
Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);



//************ SET FORM MODE ***************
$USER_CANPRINT_TAX="0";

if (GetParam(PRIMARY_KEY,"")) {
        $FormMode = "Edit";
        $USER_CANPRINT="1";
        $SQL ="SELECT vat FROM ais_memorial WHERE nobkt='".GetParam(PRIMARY_KEY,"")."' AND urut=999 ";
        if (strlen($DBConnection->dbc->get_var($SQL))) $USER_CANPRINT_TAX="1";
} else {
        $FormMode = "Add";
        $USER_CANPRINT="0";
}
//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY urut";
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************



//edited by Adit van Smith

//GET Kurs
$SQLGetKurs = "SELECT * FROM ais_kurssi WHERE curr = 'USD' ORDER BY tglbkt DESC";
$ResultGetKurs  = $DBConnection->dbc->get_row($SQLGetKurs,ARRAY_A);   

$kursUSD = $ResultGetKurs['rate'];
//END GET Kurs




$HeaderFields = array("jo_id"=>"","jo_code"=>"","project_id"=>"project_id","debtur"=>"debtur","staff_id"=>"staff_id","jo_date"=>"date","rbt_idr"=>"","rbt_usd"=>"","rat_idr"=>"","rat_usd"=>"","jo_appv_status" => "");

//Leave Here Untouch
$FormHName     = BuildHTMLField($HeaderFields,"name",1);
$FormHValue    = BuildHTMLField($HeaderFields,"value",1);



//********************************* HTML GRID *********************************************
//HTML Grid

$SQLGrid = "SELECT * FROM tblshipping_doc_upload 
            WHERE jo_id ='".$jo_id."' ORDER BY jo_id ";

$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************

function redirectMeta($url)
{
	echo "Redirecting.... Please Wait.....";
	echo "<meta http-equiv='refresh' content='0;url=".$url."'>";
}


function FormInsert() {
        global $DBConnection,$FileName;
        $DBConnection->Insert();
        header("Location: $FileName?PageMode=Form");
        exit;
}

function FormUpdate() {
        global $DBConnection;
        $DBConnection->Update();
}

function FormDelete() {
        global $DBConnection,$FileName,$TableName;
        $DBConnection->deleteGrid("$TableName","nobkt");
        header("Location: $FileName");
        exit;
}

function FormSearch () {

}

function FormCancel () {
        global $FileName;
        header("Location: ".$FileName."?PageMode=List");
        exit;
}


function DeleteRecord($sequence_name,$PageSize) 
{
	global $DBConnection,$FileName,$TableName,$upload_dir;
    
    for ($x=1;$x<=$PageSize;$x++) 
    {
       if (GetParam($sequence_name.$x,"")){           
           
           $SQLGetFile = "SELECT file_upload FROM ".$TableName." WHERE upload_doc_id = '".GetParam($sequence_name.$x,"")."'";
		   $ResultGetFile  = $DBConnection->dbc->get_row($SQLGetFile,ARRAY_A);
           $file_deleted = $ResultGetFile['file_upload'];
           
           @unlink($upload_dir.$file_deleted);
           
           $SQL = "DELETE FROM ".$TableName." WHERE upload_doc_id = '".GetParam($sequence_name.$x,"")." ' ";
           $DBConnection->dbc->query($SQL);           
       }
    }
    
	
}


function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey, $PrimaryKeyVal="") {	    
        global $FileName, $MaxGrid, $DBConnection, $upload_dir;
        
        $TotalData = $MaxGrid * 2;
        $NewDataStart = GetParam("NewData","0");
        $NewDataStart = 1;
        
        
        for ($a=1;$a<=$MaxGrid;$a++) {
	    //Begin For

            
            if ($_FILES["file_upload".$a]["name"])            
            {
			//Begin Check if Empty Keyfield	            
                 
                foreach ($FormFields as $key=>$formatting) 
                {
                                            
					$value = GetParam($key.$a,"");
					
					if($key == "$PrimaryKey")
					{
					   continue;					   
					}
					
					else if($key == "file_upload")
					{  
					   if(file_exists($upload_dir.$_FILES["file_upload".$a]["name"]))
					   {
						  echo "File ".$_FILES["file_upload".$a]["name"]." Already Exist <br>";   
					   }
					   else
					   {
					      $DBConnection->add_data($table,"jo_id",$PrimaryKeyVal);
					      $DBConnection->add_data($table,$key,$_FILES["file_upload".$a]["name"]);
					      move_uploaded_file($_FILES["file_upload".$a]["tmp_name"],$upload_dir.$_FILES["file_upload".$a]["name"]);
					   }					   					   
					   
					}

					else
					{
					   $DBConnection->add_data($table,$key,$value);
					}

                        
                }

               

                if (strlen($SpecialCase)) 
                {
                        foreach ($SpecialCase as $key => $value) 
                        {
                                $DBConnection->add_data($table,$key,$value);
                        }
                }


                if ($a < $NewDataStart) 
                {
                         if (strlen($PrimaryKey)) 
                         {
                            $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
                         } 
                         else 
                         {
                            $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
                         }
                } 
                
                else 
                {
                        $DBConnection->InsertGrid();
//                        $DBConnection->dbc->debug();
                }
            
            
            //End Check if Empty Keyfield
            }
            
            
        //End For    
        }
        $DBConnection->ClearData();
}


//*************** USER FUNCTION *******************

function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        foreach ($arrayfield as $key=>$Formatting) {
            $value = GetParam($key,"");
            if ($Formatting=="date") {
                list($day,$month,$year) = explode("/",$value);
                $value = "$year-$month-$day";
            } elseif ($Formatting=="number") $value = str_replace(",","",$value);
            $DBConnection->add_htmlfield($table,$key,$value);
        }
}



function BuildFields ($FormFields) {
                global $DBConnection;
                $str = "";
                foreach ($FormFields as $key=>$formatting) {
                        if (strlen($str)) $str .= ",$key";
                        else $str = "$key";
                }
                return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
                global $DBConnection;
                $array_fields = array();
                for ($x=0;$x<$MaxGrid;$x++) {
                        foreach ($FormFields as $key=>$formatting){
                                $a=$x+1;
                                $array_fields[$key.$a] = "$formatting";
                        }
                }
                return $array_fields;
}

function FlushCustomer ($TableName, $tmp) {
        global $DBConnection;

        if ($tmp) $TEMPORARY = "TEMPORARY";
        $DBC = new mydb(DB_USER, DB_PASSWORD, DB_NAME2, DB_HOST);

        $SQL = "SELECT kodecustomer,nama,cr_term,kdtype FROM customer ";
        if (GetParam("kdtype","")) $SQL .= " WHERE kdtype='".GetParam("kdtype","")."'";
        $MyResult = $DBC->dbc->get_results($SQL,ARRAY_N);
        if (!$MyResult) return false;
         $session_file = substr(md5(time()), 0, 8);
           $session_file = "/tmp/".$session_file.".tmp";
        BufferToFile ($MyResult,$session_file);

        $DBConnection = new mydb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
        $SQL = "DROP TABLE IF EXISTS `$TableName`;";
        $DBConnection->dbc->query($SQL);

        $SQL= "CREATE $TEMPORARY TABLE `$TableName` (
                          `kodecustomer` varchar(20) NOT NULL default '',
                          `nama` varchar(50) default NULL,
                          `cr_term` int(4) default NULL,
                          `kdtype` varchar(20) default NULL
                          )";
        $DBConnection->dbc->query($SQL);

           $SQL = "LOAD DATA INFILE '$session_file' INTO TABLE $TableName FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'";
        $DBConnection->dbc->query($SQL);
        unlink($session_file);
        return true;
}

function GetLastDateReport() {
        global $DBConnection;
        list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
        $current_date = "$year-$month-$day";

    $SQL = "DELETE FROM ais_piutang_sisa WHERE aging_date>='$current_date' ";
    if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
    if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";
    $DBConnection->dbc->query($SQL);
    //$DBConnection->dbc->debug();

        $SQL = "SELECT max(aging_date) FROM ais_piutang_sisa WHERE aging_date<='$current_date' ";
        if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";

        return $DBConnection->dbc->get_var($SQL);
}

function convert_code($code,$digit)
{
		
	$length = strlen($code);	
	$tot_str = $digit - $length;	
	$code_edit = "";
	
	for($i=0;$i < $tot_str; $i++)
	{
		$code_edit.= "0";
	}
	
	$code_edit.= $code;
	
	return $code_edit;
	
}

function convert_date($dateVar)
{
	list($day,$month,$year) = explode("/",$dateVar);
    $dateResult  = "$year-$month-$day";	
    
    return $dateResult;
}



?>
